import React, { Component } from 'react';
import { HashRouter as Router, Route, Link, Switch, Redirect } from "react-router-dom";

let token = false;
class App extends Component {
  render() {
    return (
      <div className="app">
        <Router>
          <nav>
            <Link exact to="/" >首页</Link>
            <Link exact to="/about" >关于</Link>
            <Link exact to="/user" >用户</Link>
            <Link exact to="/wallet" >钱包</Link>
          </nav>
          <section>
            <Switch>
              <Route exact component={Home} path="/"></Route>
              <Route component={About} path="/about"></Route>
              <Route component={Login} path="/login"></Route>
              <PrivateRoute component={User} path="/user"></PrivateRoute>
              <PrivateRoute component={Wallet} path="/wallet"></PrivateRoute>
            </Switch>
          </section>
        </Router>
      </div>
    );
  }
}

const Home = () => <div>首页</div>
const About = () => <div>关于</div>
const User = () => <div>用户</div>
const Wallet = () => <div>钱包</div>

const Login = (props) => {
  const handleLogin = () => {
    token = true;
    props.history.replace(props.location.state)
  }

  return <div>
    <h1>登录</h1>
    <button onClick={handleLogin}>点击登录</button>
  </div>;
}

class PrivateRoute extends Component {
  render() {
    if (token) {
      return < Route {...this.props} />
    } else {
      return <Redirect to={{ pathname: "/login", state: this.props.location.pathname }}  ></Redirect>
    }
  }
}


export default App;